<template>
  <div v-loading="loading" class="dashboard-container">
    <div class="app-container">
      <!-- 头部 -->
      <el-tabs v-model="activeName">
        <el-tab-pane label="组织架构" name="first" />
      </el-tabs>
      <el-card class="tree-card">
        <!-- 使用 -->
        <tree-tools :tree-node="company" :is-root="true" @addDept="addDept" />
        <!-- 左侧 -->
        <el-tree
          :data="departs"
          :props="defaultProps"
          :default-expand-all="true"
        >
          <!-- 使用 -->
          <tree-tools
            slot-scope="{ data }"
            :tree-node="data"
            @addDept="addDept"
            @delDpts="getDepartments"
            @editDepts="editDepts"
          /></el-tree>
      </el-card>
    </div>
    <!-- 放置新增弹层组件  -->
    <add-dept
      ref="addDept"
      :show-dialog.sync="showDialog"
      :tree-node="node"
      @addDepts="getDepartments"
    />
  </div>
</template>

<script>
// 引入
import treeTools from './components/tree-tools.vue'
import { getDepartments } from '@/api/departments'
import { tranListToTreeData } from '@/utils'
import AddDept from './components/add-dept.vue' // 引入新增部门组件
export default {
  // 注册
  components: { treeTools, AddDept },
  data() {
    return {
      loading: true, // 控制弹层的显示和影藏
      showDialog: false,
      activeName: 'first',
      company: { name: '', manager: '' },
      departs: [],
      defaultProps: { label: 'name', children: 'children' },
      node: null
    }
  },
  created() {
    this.getDepartments()
  },
  methods: {
    //   1-获取组织架构
    async getDepartments() {
      this.loading = true
      const res = await getDepartments()
      this.company = { name: res.companyName, manager: '负责人', id: '' }
      this.departs = tranListToTreeData(res.depts, '')
      this.loading = false
    },
    // 2-新增部门
    addDept(node) {
      this.showDialog = true // 显示弹层
      this.node = node // 因为node是当前的点击的部门， 此时这个部门应该记录下来,
    },
    // 3-编辑部门
    editDepts(node) {
      this.showDialog = true
      this.node = node // 存储传过来的node数据
      // 父组件调用子组件的方法
      this.$refs.addDept.getDepartDetail(node.id) // 直接调用子组件的方法，传入id
    }
  }
}
</script>

<style scoped>
.tree-card {
  padding: 30px 140px;
  font-size: 14px;
}
</style>
